<?php

namespace App\Http\Controllers\Personal;
use App\Models\Common\CollArea;
use App\Models\Common\CollOption;
use App\Models\Company\CompanyJob;
use App\Models\Personal\Favorites;
use App\Models\Personal\Resume;
use App\Models\Personal\ResumeSend;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Style;

/**
 * @param //
 * 创建时间 2016-8-13
 **/
class FavoritesController extends CommonController{
    /**
     * 职位收藏夹
     * @param Request $request
     * @return mixed
     */
    public function favorites(Request $request){
        $user = auth()->guard('personal')->user();
        //关键词搜索
        $keyword  = trim($request->keyword);
        $job_status  = $request->job_status;
        //查询是否已投先觉条件
        if($job_status == '1'){
            $exFun="WhereExists";
        }else if($job_status == '2'){
            $exFun="WhereNotExists";
        }else{
            $exFun="Where";
        }

        $favorites = DB::table('favorites as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            //->leftjoin('resume_send as t4', 't1.job_id', '=', 't4.job_id')
            ->select(
                't1.id','t1.created_at','t1.com_id','t1.job_id',
                't2.company_name','t2.region',
                't3.job_title','t3.salary_above','t3.salary_below','t3.location1'
            )
            ->where('t1.uid',$user->uid)
            ->{$exFun}(function ($query) use ($job_status,$user)  {
                if($job_status != '') {
                    $query->select('status')->from('resume_send as t4')
                        ->whereRaw(env('DB_PREFIX')."t1.job_id = ".env('DB_PREFIX')."t4.job_id")
                        ->where('t4.personal_uid', $user->uid)
                        ->where('t4.status', '!=', 4);
                }
            })

            ->where(function ($query) use ($keyword) {
                if(strlen($keyword) > 0){
                    $query->where('t3.job_title', 'like', '%'.$keyword.'%')
                        ->orWhere('t2.company_name','like','%'.$keyword.'%');
                }
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        //dd($favorites);
        //处理数组
        foreach($favorites as $v){
            $v->company_name = str_limit($v->company_name,24);
            $v->job_title = str_limit($v->job_title,24);
            $v->region = str_limit(str_replace(',','',CollArea::getCityAddress($v->region)),20);
            $v->location1  = ($v->location1) ?  CollArea::getAreaName($v->location1) : '';
            $v->salary_above = ($v->salary_above) ? CollOption::getOptionName($v->salary_above,'expectedsalary') : '';
            $v->salary_below = ($v->salary_below) ? CollOption::getOptionName($v->salary_below,'expectedsalary') : '';
            $v->created_at = substr($v->created_at,0,10);
            $v->status  =DB::table('resume_send')->select('status')
                            ->where("job_id",$v->job_id)
                            ->where('personal_uid', $user->uid)
                            ->where('status', '!=', 4)->count();
        }
        //dd($favorites);
        //分页分配参数 过滤boolean假值
        $appends =arrayFilter(array(
            'keyword' => $keyword,
            'job_status' =>  $job_status
        ));
        return Style::view('personal.favorites',compact('favorites','job_status','appends'));
    }

    /**
     * 收藏职位批量投递
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function favoritesSend(Request $request){
        $user = auth()->guard('personal')->user();
        //判断有没有简历ID
        $resume = Resume::where('uid',$user->uid)->first(['id']);
        if($resume){
            $input = [];
            //获取职位id
            $job_id = $request->input('selected_id.*');
            $job_id = array_unique($job_id);
            foreach($job_id as $k => $v){
                $ResumeSend = ResumeSend::where('job_id',$v)->where('personal_uid',$user->uid)->where('resume_id',$resume->id)
                    ->orderBy('updated_at','desc')->first(['id','updated_at']);
                if(count($ResumeSend) > 0){
                    //判断是不是当天投递简历
                    if( strtotime($ResumeSend['updated_at']) + 24*3600 > time() ){
                        $input['updated_at'] = date('Y-m-d H:i:s',time());
                        ResumeSend::where('id',$ResumeSend['id'])->where('personal_uid',$user->uid)->update($input);
                    }else{
                        $CompanyJob = CompanyJob::where('id',$v)->first(['uid','com_id']);
                        $input['company_uid'] = $CompanyJob->uid;
                        $input['com_id'] = $CompanyJob->com_id;
                        $input['personal_uid'] = $user->uid;
                        $input['resume_id'] = $resume->id;
                        $input['job_id'] = $v;
                        //插入投递记录
                        ResumeSend::create($input);
                    }
                }else{
                    $CompanyJob = CompanyJob::where('id',$v)->first(['uid','com_id']);
                    $input['company_uid'] = $CompanyJob->uid;
                    $input['com_id'] = $CompanyJob->com_id;
                    $input['personal_uid'] = $user->uid;
                    $input['resume_id'] =  $resume->id;
                    $input['job_id'] = $v;
                    //插入投递记录
                    ResumeSend::create($input);
                }
            }
            return redirect('personal/favorites');
        }else{
            return redirect('personal/my_resume');
        }
    }

    /**
     * 单个职位收藏夹删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function favoritesCurrDel(Request $request){
        $user = auth()->guard('personal')->user();
        if(!empty($request->id)){
            $result = Favorites::where('id',$request->id)->where('uid',$user->uid)->delete();
            if($result){
                return response()->json(['status' => 0,'msg' => '职位收藏夹删除成功！']);
            }else{
                return response()->json(['status' => 1,'msg' => '职位收藏夹删除失败，请稍后重试！']);
            }
        }else{
            return response()->json(['status' => 1,'message'=>"职位收藏夹删除失败，请稍后重试！"]);
        }
    }

    /**
     * form职位收藏状态返回
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function personfavorites(Request $request){
        $applyJobStatus = 1;
        $applyJobMsg = '123';
        $input = $request->only('jobid','comid');
        $jobid = $input['jobid'];
        $comid = $input['comid'];
        //个人用户登录
        $user=auth()->guard('personal')->user();
        if(!empty($user->uid) and is_numeric($user->uid)) {//登录
            $personFavorites = Favorites::where('job_id',$jobid)->where('uid',$user->uid)->first();
            if($personFavorites){//有
                $applyJobStatus = 1;
                $applyJobMsg = "取消收藏";
                Favorites:: where('job_id',$jobid)->where('uid',$user->uid)->take(1)->delete();
            }else{//无
                $applyJobStatus = 0;
                $applyJobMsg= "收藏成功";
                $favoritesData['uid']=$user->uid;
                $favoritesData['com_id']=$comid;
                $favoritesData['job_id']=$jobid;
                $favoritesData['created_at']=date('Y-m-d H:m:s');
                $favoritesData['updated_at']=date('Y-m-d H:m:s');
                Favorites::create($favoritesData);
            }
        }
        return response()->json(['status' => $applyJobStatus, 'msg' => "$applyJobMsg"]);
    }
}